#include <iostream>
#include "UdpServer.hpp"
#include "log.hpp"
#include "InetAddr.hpp"
#include <string>
#include <memory>

#include "Thread.hpp"
#include"Comm.hpp"
using namespace ThreadModule;
void Usage(std::string str)
{
    std::cout << "Usage:\n\t" << str << " _local_port\n"
              << std::endl;
}
int InitClient(std::string &serverip, uint16_t serverport, struct sockaddr_in *server)
{
    // 创建socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error " << std::endl;
        return -1;
    }
    // 构建目标主机的socket信息
    memset(server, 0, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());
    return sockfd;
}
void recvmessage(int sockfd, std::string name)
{
    // int fd = openDev("/dev/pts/4",O_WRONLY);
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            fprintf(stderr,"[%s]%s\n",name.c_str(),buffer);
            // write(fd,buffer,sizeof(buffer));
        }
    }
}
void sendmessage(int sockfd, struct sockaddr_in &server, std::string name)
{
    std::string message;
    while (true)
    {
        printf("%s  | enter# ", name.c_str());
        fflush(stdout);
        std::getline(std::cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));//向目标服务器的IP和端口好号：发送信息
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serveip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    int sockfd = InitClient(serveip, serverport, &server);//创建套接字，并在server结构体中写入，要接受的ip 和端口号，
    if (sockfd == -1)
    {
        return 1;
    }
    func_t r = std::bind(&recvmessage, sockfd, std::placeholders::_1);//recvmessage函数绑定参数sockfd，std::placeholders::_1：recvmessage函数只用输入一个参数即可
    func_t s = std::bind(&sendmessage, sockfd, server, std::placeholders::_1);//sendmessage函数绑定参数sockfd，server，std::placeholders::_1：sendmessage函数只用输入一个参数，
    //server该结构体包含了目标服务器的IP地址和端口号。
    Thread Recver(r, "recver");//创建接收线程，一直接收信息，可以接收来自sockfd的任意信息，执行r函数
    Thread Sender(s, "sender");//创建发送线程，当想发送信息时，可以立即发送、执行s函数

    Recver.Start();//启动线程
    Sender.Start();
    Recver.Join();//等待线程
    Sender.Join();
    return 0;
}
